package com.qf.cloud2203.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class TestFilter extends ZuulFilter {

    /**
     * 过滤器的类型，前置，后置
     * @return
     */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    /**
     * 过滤器的序号，越小排序越考前
     * @return
     */
    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER-1;
    }

    /**
     * 当前过滤器是否生效
     * @return
     */
    @Override
    public boolean shouldFilter() {
        // 如果要动态设计，可以从 redis中读取 过滤器是否生效的配置信息
        return true;
    }

    /**
     * 处理请求的通用逻辑，写在这里
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {

        System.out.println("================TestFilter===================");

        final RequestContext requestContext = RequestContext.getCurrentContext();

        final HttpServletRequest request = requestContext.getRequest();

        final String token = request.getParameter("token");

        System.out.println(token);

        // 校验token有效性
        if (token==null || !token.equals("123456")){
            // 请求就此打住，不要再发送给后面的微服务了额
            requestContext.setSendZuulResponse(false);

            // 返回 token校验失败的信息
            final HttpServletResponse response = requestContext.getResponse();
            response.setContentType("text/html;charset=utf-8");
            try {
                response.getWriter().println("token校验失败，请重新申请token");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }
}
